package org.apache.zookeeper.server.paxos2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;

/**
 * Created by IntelliJ IDEA.
 * User: wangw
 * Date: 2011-6-12
 * Time: 21:43:54
 * To change this template use File | Settings | File Templates.
 */
public class FetchBlocksResponse extends Message {

    public int sid;
    public long[] blockIds;
    public byte[][] data;
    
	public FetchBlocksResponse(){}

    public FetchBlocksResponse(int size){
        blockIds = new long[size];
        data = new byte[size][];
    }
    
    @Override
	public void deserialize(DataInputStream in) throws IOException {
    	sid = in.readInt();
        int size = in.readInt();
        blockIds = new long[size];
        for(int i=0; i<size; i++){
            blockIds[i] = in.readLong();
        }
        data = new byte[size][];
        for(int i=0; i<size; i++){
            int tmp = in.readInt();
            if(tmp==0)
                data[i]=null;
            else{
                data[i] = new byte[tmp];
                in.readFully(data[i]);
            }
        }
		
	}

	@Override
	public void serialize(DataOutputStream out) throws IOException {
		assert blockIds.length == data.length;
		out.writeInt(sid);
        out.writeInt(blockIds.length);
        for(int i=0; i<blockIds.length; i++)
            out.writeLong(blockIds[i]);
        for(int i=0; i<data.length; i++){
            if(data[i]==null)
                out.writeInt(0);
            else{
                out.writeInt(data[i].length);
                out.write(data[i]);
            }

        }
		
	}
}
